package com.modbus.tcp.service;

import com.modbus.tcp.utils.Modbus4jReader;
import com.modbus.tcp.utils.Modbus4jWriter;
import com.serotonin.modbus4j.exception.ErrorResponseException;
import com.serotonin.modbus4j.exception.ModbusInitException;
import com.serotonin.modbus4j.exception.ModbusTransportException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ModbusTcpService {

    @Autowired
    private Modbus4jReader modbus4jReader;

    @Autowired
    private Modbus4jWriter modbus4jWriter;


    public short[] readHoldingRegister(String ipAdd,int ipPort,boolean ifRtu,int slaveId, int offset, int numberOfBits)throws ModbusTransportException, ErrorResponseException, ModbusInitException {
        return  modbus4jReader.readHoldingRegister( ipAdd, ipPort, ifRtu,slaveId, offset,numberOfBits);
    }

    public   short[] readInputRegisters(String ipAdd,int ipPort,boolean ifRtu,int slaveId, int offset, int numberOfBits)throws ModbusTransportException, ErrorResponseException, ModbusInitException {
        return  modbus4jReader.readInputRegisters( ipAdd, ipPort, ifRtu,slaveId, offset,numberOfBits);
    }

    public boolean writeRegister(String ipAdd,int ipPort,boolean ifRtu,int slaveId, int writeOffset, short writeValue) throws ModbusTransportException, ErrorResponseException, ModbusInitException {
        return  modbus4jWriter.writeRegister( ipAdd, ipPort, ifRtu, slaveId,  writeOffset,  writeValue);
    }

}
